<?php
// +----------------------------------------------------------------------
// | Description: 回款
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com 
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\crm\model\Contract;
use think\Hook;
use think\Request;
use think\Db;

class Receivables extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
    **/    
    public function _initialize()
    {
        $action = [
            'permission'=>['month'],
            'allow'=>['check','revokecheck']
        ];
        Hook::listen('check_auth',$action);
        $request = Request::instance();
        $a = strtolower($request->action());        
        if (!in_array($a, $action['permission'])) {
            parent::_initialize();
        }
    }
    /**
     * 数据导入
     */
    public function dataAdd(){
        $customerData=[
            "name"=>"四川锦都蜀王府餐饮管理有限公司",//公司名称
            "deal_status"=>"已成成交",//成交状态
            "deal_time"=>(time()-3600*24*180),//成交时间
            "level"=>"A",//客户等级
            "mobile"=>"18628189173",//手机号
            "crm_aloelf"=>"",//客户姓名
            "create_user_id"=>"8",//创建人ID
            "owner_user_id"=>"8",//负责人ID
            "create_time"=>time(),//创建时间
        ];

        $customer=db("customer")->where(["id"=>1])->find();
        var_dump($customer);exit;
    }
    /**
     * 回款列表
     * @author Michael_xu
     * @return 
     */
    public function index()
    {
        $receivablesModel = model('Receivables');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];        
        $data = $receivablesModel->getDataList($param);       
        return resultArray(['data' => $data]);
    }

    /**
     * 添加回款
     * @author Michael_xu
     * @param 
     * @return 
     */
    public function save()
    {
        $receivablesModel = model('Receivables');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $examineStepModel = new \app\admin\model\ExamineStep();
        $param['create_user_id'] = $userInfo['id'];
        $param['owner_user_id'] = $userInfo['id'];
        $param['crm_lasahm']="正常核算";//默认都是正常核算
        //审核判断（是否有符合条件的审批流）
        $examineFlowModel = new \app\admin\model\ExamineFlow();
        if (!$examineFlowModel->checkExamine($param['owner_user_id'], 'crm_receivables')) {
            return resultArray(['error' => '暂无审批人，无法创建']); 
        }
        //添加审批相关信息
        $examineFlowData = $examineFlowModel->getFlowByTypes($param['owner_user_id'], 'crm_receivables');
        if (!$examineFlowData) {
            return resultArray(['error' => '无可用审批流，请联系管理员']);
        }
        $param['flow_id'] = $examineFlowData['flow_id'];
        //获取审批人信息
        if ($examineFlowData['config'] == 1) {
            //固定审批流
            $nextStepData = $examineStepModel->nextStepUser($userInfo['id'], $examineFlowData['flow_id'], 'crm_receivables', 0, 0, 0);
            $next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : '';
            $check_user_id = $next_user_ids ? : [];
            $param['order_id'] = 1;
        } else {
            $check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
        }
        if (!$check_user_id) {
            return resultArray(['error' => '无可用审批人，请联系管理员']);
        }
        $param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id;
        //流程审批人
        // $flow_user_id = $examineFlowModel->getUserByFlow($examineFlowData['flow_id'], $param['owner_user_id']); 
        // $param['flow_user_id'] = $flow_user_id ? arrayToString($flow_user_id) : '';                

        $res = $receivablesModel->createData($param);
        if ($res) {
            return resultArray(['data' => '添加成功']);
        } else {
            return resultArray(['error' => $receivablesModel->getError()]);
        }
    }

    /**
     * 回款详情
     * @author Michael_xu
     * @param  
     * @return 
     */
    public function read()
    {
        $receivablesModel = model('Receivables');
        $userModel = new \app\admin\model\User();
        $param = $this->param;
        $data = $receivablesModel->getDataById($param['id']);
        $userInfo=$this->userInfo;
        //判断权限
        $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'read');
        if (!in_array($data['owner_user_id'],$auth_user_ids) && !in_array($userInfo["id"],$auth_user_ids)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>102,'error'=>'无权操作']));
        }         
        if (!$data) {
            return resultArray(['error' => $receivablesModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 编辑回款
     * @author Michael_xu
     * @param 
     * @return 
     */
    public function update()
    {    
        $receivablesModel = model('Receivables');
        $userModel = new \app\admin\model\User();
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $param['create_user_id'] = $userInfo['id'];
        //判断权限
        $dataInfo = $receivablesModel->getDataById($param['id']);
        $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'update');
        if (!in_array($dataInfo['owner_user_id'],$auth_user_ids)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>102,'error'=>'无权操作']));
        }

        //已进行审批，不能编辑
        if (in_array($dataInfo['check_status'],['2'])) {
            return resultArray(['error' => '审核通过订单，不可编辑']);
        }

        //将回款审批状态至为待审核，提交后重新进行审批
        //审核判断（是否有符合条件的审批流）
        $examineFlowModel = new \app\admin\model\ExamineFlow();
        $examineStepModel = new \app\admin\model\ExamineStep();
        if (!$examineFlowModel->checkExamine($param['create_user_id'], 'crm_receivables')) {
            return resultArray(['error' => '暂无审批人，无法创建']); 
        }
        //添加审批相关信息
        $examineFlowData = $examineFlowModel->getFlowByTypes($param['create_user_id'], 'crm_receivables');
        if (!$examineFlowData) {
            return resultArray(['error' => '无可用审批流，请联系管理员']);
        }
        $param['flow_id'] = $examineFlowData['flow_id'];
        //获取审批人信息
        if ($examineFlowData['config'] == 1) {
            //固定审批流
            $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $examineFlowData['flow_id'], 'crm_receivables', 0, 0, 0);
            $next_user_ids = arrayToString($nextStepData['next_user_ids']) ? : '';
            $check_user_id = $next_user_ids ? : [];
            $param['order_id'] = 1;
        } else {
            $check_user_id = $param['check_user_id'] ? ','.$param['check_user_id'].',' : '';
        }
        if (!$check_user_id) {
            return resultArray(['error' => '无可用审批人，请联系管理员']);
        }
        $param['check_user_id'] = is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id;
        $param['check_status'] = 0;   

        //流程审批人
        // $flow_user_id = $examineFlowModel->getUserByFlow($examineFlowData['flow_id'], $dataInfo['owner_user_id']);
        // $param['flow_user_id'] = $flow_user_id ? arrayToString($flow_user_id) : '';
        $param['flow_user_id'] = '';

        $res = $receivablesModel->updateDataById($param, $param['id']);
        if ($res) {
            //将审批记录至为无效
            $examineRecordModel = new \app\admin\model\ExamineRecord();
            $examineRecordModel->setEnd(['types' => 'crm_receivables','types_id' => $param['id']]);            
            return resultArray(['data' => '编辑成功']);
        } else {
            return resultArray(['error' => $receivablesModel->getError()]);
        }       
    }

    /**
     * 删除回款
     * @author Michael_xu
     * @param 
     * @return 
     */
    public function delete()
    {
        $receivablesModel = model('Receivables');
        $param = $this->param;
        $userInfo = $this->userInfo;      
        if (!is_array($param['id'])) {
            $receivables_id = [$param['id']];
        } else {
            $receivables_id = $param['id'];
        }
        $delIds = [];
        $errorMessage = [];

        //数据权限判断
        $userModel = new \app\admin\model\User();
        $auth_user_ids = $userModel->getUserByPer('crm', 'receivables', 'delete');
        $adminTypes = adminGroupTypes($userInfo['id']);
        foreach ($receivables_id as $k=>$v) {
            $isDel = true;
            //数据详情
            $data = $receivablesModel->getDataById($v);
            if (!$data) {
                $isDel = false;
                $errorMessage[] = 'id为'.$v.'的回款删除失败,错误原因：'.$receivablesModel->getError();
                continue;
            }
            if (!in_array($data['owner_user_id'],$auth_user_ids)) {
                $isDel = false;
                $errorMessage[] = '名称为'.$data['number'].'的回款删除失败,错误原因：无权操作';
                continue;
            }
            if (!in_array($data['check_status'],['4']) && !in_array(1,$adminTypes)) {
                $isDel = false;
                $errorMessage[] = '名称为'.$data['number'].'的回款删除失败,错误原因：请先撤销审核';
                continue;
            }            
            $delIds[] = $v;            
        }
        if ($delIds) {
            $data = $receivablesModel->delDatas($delIds);
            if (!$data) {
                return resultArray(['error' => $receivablesModel->getError()]);
            } 
            actionLog($delIds,'','','');         
        }
        if ($errorMessage) {
            return resultArray(['error' => $errorMessage]);
        } else {
            return resultArray(['data' => '删除成功']);
        }            
    }    
    
    /**
     * 回款审核
     * @author Michael_xu
     * @param 
     * @return
     */  
    public function check()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $user_id = $userInfo['id'];
        $receivablesModel = model('Receivables');
        $examineStepModel = new \app\admin\model\ExamineStep();
        $examineRecordModel = new \app\admin\model\ExamineRecord();
        $examineFlowModel = new \app\admin\model\ExamineFlow();

        $receivablesData = [];
        $receivablesData['update_time'] = time();
        $receivablesData['check_status'] = 1; //0待审核，1审核通中，2审核通过，3审核未通过
        //权限判断
        if (!$examineStepModel->checkExamine($user_id, 'crm_receivables', $param['id'])) {
           return resultArray(['error' => $examineStepModel->getError()]); 
        };
        //审批主体详情
        $dataInfo = $receivablesModel->getDataById($param['id']);
        $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
        $is_end = 0; // 1审批结束

        $status = $param['status'] ? 1 : 0; //1通过，0驳回
        $checkData = [];
        $checkData['check_user_id'] = $user_id;
        $checkData['types'] = 'crm_receivables';
        $checkData['types_id'] = $param['id'];
        $checkData['check_time'] = time();
        $checkData['content'] = $param['content'];
        $checkData['flow_id'] = $dataInfo['flow_id'];
        $checkData['order_id'] = $dataInfo['order_id'] ? : 1;
        $checkData['status'] = $status;

        $contract=\app\crm\model\Contract::where(["contract_id"=>$dataInfo["contract_id"]])->find();
        if ($status == 1) {
            if ($flowInfo['config'] == 1) {
                //固定流程
                //获取下一审批信息
                $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_receivables', $param['id'], $dataInfo['order_id'], $user_id);
                $next_user_ids = $nextStepData['next_user_ids'] ? : [];
                $receivablesData['order_id'] = $nextStepData['order_id'] ? : '';
                if (!$next_user_ids) {
                    $is_end = 1;
                    //审批结束
                    $checkData['check_status'] = !empty($status) ? 2 : 3;
                    $receivablesData['check_user_id'] = '';
                } else {
                    //修改主体相关审批信息
                    $receivablesData['check_user_id'] = arrayToString($next_user_ids);
                }                 
            } else {
                //自选流程
                $is_end = $param['is_end'] ? 1 : '';
                $check_user_id = $param['check_user_id'] ? : '';
                if ($is_end !== 1 && empty($check_user_id)) {
                    return resultArray(['error' => '请选择下一审批人']); 
                }
                $receivablesData['check_user_id'] = arrayToString($param['check_user_id']);
            } 
            if ($is_end == 1) {
                $checkData['check_status'] = !empty($status) ? 2 : 3;
                $receivablesData['check_user_id'] = '';
                $receivablesData['check_status'] = 2;
                //2024-1-19 修改回款编号
                if($dataInfo["crm_lasahm"]=="正常核算"){
                    $year=date("Y");
                    $month=date("m");
                    $financeNumber=Db::name("crm_finance")
                        ->where("YEAR(check_time)={$year} and MONTH(check_time)={$month} and calculate_way != '暂不核算'")
                        ->where(["department"=>$contract["crm_kfhgfp"],"order_type"=>["in",["成本变更","退款","回款"]],"check_status"=>"2"])->count();
                    $financeNumber=$financeNumber>0?str_pad($financeNumber+1,4,"0",STR_PAD_LEFT):"0001";//财务编号
                    $receivablesData["number"]=substr($contract["crm_kfhgfp"],0,1)."-".date("Y")."-".date("m")."-".$financeNumber;//回款表中的编号和财务表编号相同
                    $receivablesData["code"]=$financeNumber;
                    $financeData["order_sn"]=$receivablesData["number"];//财务表的编号--财务表专用
                }
            }                     
        } else {
            //审批驳回
            $is_end = 1;
            $receivablesData['check_status'] = 3;
            //将审批记录至为无效
            // $examineRecordModel->setEnd(['types' => 'crm_receivables','types_id' => $param['id']]);                       
        }
        /***********************财务表更新******************************/
        $financeData["check_status"]=$receivablesData['check_status'];//审核状态
        $financeData["check_time"]=date("Y-m-d H:i:s");//审核时间
        $financeData["remarks"]=$param['content'];//备注
        db("crm_finance")->where(["relation_id"=>$param['id'],"order_type"=>"回款"])->update($financeData);
        /***********************财务表更新******************************/
        //已审批人ID
        $receivablesData['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']),[$user_id])) : arrayToString([$user_id]);        
        $resReceivables = db('crm_receivables')->where(['receivables_id' => $param['id']])->update($receivablesData);

        if ($resReceivables) {
            if ($status) {
                //发送站内信
                $sendContent = '您的申请【'.$dataInfo['number'].'】,'.$userInfo['realname'].'已审核通过';
                $resMessage = sendMessage($dataInfo['owner_user_id'], $sendContent, $param['id'], 1);
            } else {
                $sendContent = '您的申请【'.$dataInfo['number'].'】,'.$userInfo['realname'].'已审核拒绝,审核意见：'.$param['content'];
                $resMessage = sendMessage($dataInfo['owner_user_id'], $sendContent, $param['id'], 1);
            }

            //审批记录
            $resRecord = $examineRecordModel->createData($checkData);
            if ($is_end == 1 && !empty($status)) {
                //发送站内信
                $sendContent = '您的申请【'.$dataInfo['number'].'】,'.$userInfo['realname'].'已审核通过,审批结束';
                $resMessage = sendMessage($dataInfo['owner_user_id'], $sendContent, $param['id'], 1);
                //2023-10-26 lina 修改 start
                $list=\app\crm\model\Contract::alias("contract")
                    ->field("customer.customer_id,customer.deal_status")
                    ->join('__CRM_CUSTOMER__ customer','contract.customer_id = customer.customer_id','LEFT')
                    ->where(["contract.contract_id"=>$dataInfo["contract_id"]])->find();
                $list["deal_status"]='';
                if($receivablesData["check_status"]==2){
                    if($list["deal_status"]!="已成交"){
                        $customerModel = new \app\crm\model\Customer();
                        //审核通过----修改客户状态为已成交
                        $customerModel->where(["customer_id"=>$list["customer_id"]])->update(["deal_status"=>"已成交"]);
                    }
                    if($dataInfo["crm_lasahm"]=="正常核算"){
                        //修改合同尾款字段
                        \app\crm\model\Contract::where(["contract_id"=>$dataInfo["contract_id"]])
                            ->setDec("arrears",$dataInfo["money"]);
                    }
                    //2023-12-21 新增 ---start
                    /* $accountingModel = model('Accounting');
                     $price=$accountingModel->monthlyAgencyPrice($dataInfo["contract_id"]);
                     \app\crm\model\Contract::where(["contract_id"=>$dataInfo["contract_id"]])->update(["monthly_agency_price"=>$price]);*/
                    //2023-12-21 新增 ---end
                }
                //2023-10-26 lina 修改 end
                //计算期数
                if(!empty($contract) && $contract["crm_wvgjii"]=="记账"){
                    $receivablesMoney=$receivablesModel->where(["contract_id"=>$dataInfo["contract_id"],"check_status"=>2,"crm_lasahm"=>"正常核算"])->sum("money");
                    $money=bcdiv($contract["total_price"],$contract["crm_grvgkz"],2);
                    //$available=empty($contract["crm_grvgkz"])?0:ceil($receivablesMoney/$money);
                    $available=(empty($contract["crm_grvgkz"]) || $contract["crm_grvgkz"]<=0)?0:floor($receivablesMoney/$money);
                    $contract->save(["available"=>$available]);
                }
            }
            return resultArray(['data' => '审批成功']);            
        } else {
            return resultArray(['error' => '审批失败，请重试！']); 
        }
    }

    /**
     * 回款撤销审核
     * @author Michael_xu
     * @param 
     * @return
     */  
    public function revokeCheck()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $user_id = $userInfo['id'];
        $receivablesModel = model('Receivables');
        $examineStepModel = new \app\admin\model\ExamineStep();
        $examineRecordModel = new \app\admin\model\ExamineRecord();
        $customerModel = model('Customer');
        $userModel = new \app\admin\model\User();

        $receivablesData = [];
        $receivablesData['update_time'] = time();
        $receivablesData['check_status'] = 0; //0待审核，1审核通中，2审核通过，3审核未通过

        //审批主体详情
        $dataInfo = $receivablesModel->getDataById($param['id']);

        //撤回时同步财务表的审核状态
        if($dataInfo["receivables_id"]){
            db("crm_finance")->where(["relation_id"=>$dataInfo["receivables_id"],"order_type"=>"回款","check_status"=>["in",["0","1"]]])->update(["check_status"=>4]);
        }
        //权限判断(创建人或负责人或管理员)
        if ($dataInfo['check_status'] == 2) {
            return resultArray(['error' => '已审批结束,不能撤销']);   
        } 
        if ($dataInfo['check_status'] == 4) {
            return resultArray(['error' => '无需撤销']);   
        }

        $admin_user_ids = $userModel->getAdminId(); 
        if ($dataInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
            return resultArray(['error' => '没有权限']);
        }     
        
        $is_end = 0; // 1审批结束
        $status = 2; //1通过，0驳回, 2撤销
        $checkData = [];
        $checkData['check_user_id'] = $user_id;
        $checkData['types'] = 'crm_receivables';
        $checkData['types_id'] = $param['id'];
        $checkData['check_time'] = time();
        $checkData['content'] = $param['content'];
        $checkData['flow_id'] = $dataInfo['flow_id'];
        $checkData['order_id'] = $dataInfo['order_id'];
        $checkData['status'] = $status;
        
        $receivablesData['check_status'] = 4;
        $receivablesData['check_user_id'] = '';
        $receivablesData['flow_user_id'] = '';
        $resReceivables = db('crm_receivables')->where(['receivables_id' => $param['id']])->update($receivablesData);
        if ($resReceivables) {
            //将审批记录至为无效
            // $examineRecordModel->setEnd(['types' => 'crm_receivables','types_id' => $param['id']]);
            //审批记录
            $resRecord = $examineRecordModel->createData($checkData);
            return resultArray(['data' => '撤销成功']);            
        } else {
            return resultArray(['error' => '撤销失败，请重试！']); 
        }
    }
    /**
     * 查找审核通过回款列表
     * */
    public function month()
    {
        $param = $_POST;
        if(!isset($param["contract_id"])) return resultArray(['error' => '请选择合同']);
        $where=["contract_id"=>$param["contract_id"],"check_status"=>2,"crm_lasahm"=>"正常核算","money"=>[">",0]];
        if($param["type"]=="3" || $param["type"]=="1"){//退过款的回款单不允许报销和调整核定成本

            // 获取所有回款编号
            $receivablesDataNew = db("crm_finance")->where(["contract_id"=>$param["contract_id"],"check_status"=>["in",[0,1,2]],"order_type"=>"回款"])->select();
            if(!empty($receivablesDataNew)) {
                $refundIds = [];
                foreach ($receivablesDataNew as $key => $value) {
                    $refund_money_new = db("crm_finance")->where(["contract_id"=>$param["contract_id"],"receivables_code"=>$value['order_sn'],"check_status"=>["in",[0,1,2]],"order_type"=>"退款"])->sum('refund_money');
                    if($refund_money_new == $value['money']) {
                        $refundIds[] = $value['order_sn'];
                    }
                }
                if($refundIds) {
                    //已退款的回款单号
                    $where["number"]=["not in",$refundIds];
                }
            }
            // $refundIds=db("crm_finance")->where(["contract_id"=>$param["contract_id"],"check_status"=>["in",[0,1,2]],"order_type"=>"退款"])->column("receivables_code");
        }
        $data=\app\crm\model\Receivables::field("receivables_id,number,crm_oeseng,money,crm_oeseng")
            ->where($where)
            ->select();
        if(!$data) return resultArray(['data' => $data]);//回款不存在直接返回
        if($param["type"]=="2"){ //退款=单笔回款金额-单笔报销金额 + 追回金额(不超过报销金额)
            //可退款金额=回款金额-待已退款金额-待已报销金额、可追回成本=已报销金额-待已追回金额
            foreach ($data as $k=>$v){
                $recoverMoney=db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"退款","check_status"=>["in",[0,1,2]]])->sum("recover_money");//已经追回的成本
                $refundMoney=db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"退款","check_status"=>["in",[0,1,2]]])->sum("should_refund_money");//已退款和正在等待审核的退款金额
                $expenseMoneySum=db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"报销","check_status"=>["in",[0,1,2]]])->sum("reimburse_money");//待已报销金额
                $expenseMoney=db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"报销","check_status"=>2])->sum("reimburse_money");//已报销金额
                $data[$k]["max_recover_money"]=bcsub($expenseMoney,$recoverMoney,2);//最大可追回的报销金额
                $data[$k]["max_refund_money"]=bcsub($v["money"],bcadd($refundMoney,$expenseMoneySum),2);//最大该回款单可退款金额
                
                // 最大可调增成本  = 累计业绩
                // 变更的成本
                $change_crm_oeseng = db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"成本变更","check_status"=>["in",[0,1,2]]])->sum("crm_oeseng");
                // 退回业绩
                $calculate=db("crm_finance")->where(["order_type"=>"退款","receivables_code"=>$v['number'],"check_status"=>["in",[0,1,2]]])->sum("calculate");
                // 回款单业绩
                $refund_calculate = bcsub($v["money"],$v["crm_oeseng"],2);
                // 最大可调增成本 = 业绩金额
                // 业绩=现有金额（回款单核算业绩+成本调整增减业绩）-退回业绩（退款申请）
                $performance = bcsub($refund_calculate,$change_crm_oeseng,2);
                //最大该回款单可退回业绩
                $data[$k]["max_refund_performance"] = bcadd($performance,$calculate,2);
            }
            


        }elseif ($param["type"]==3){//报销 可报销金额=核定成本-待已报销金额
            foreach ($data as $k=>$v){
                $expenseMoneySum=db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"报销","check_status"=>["in",[0,1,2]]])->sum("reimburse_money");//待已报销金额
                $data[$k]["max_expense_money"]=bcsub($v["crm_oeseng"],$expenseMoneySum,2);//最大可报销金额
                if($data[$k]["max_expense_money"]==0) unset($data[$k]);
            }
            sort($data);
        }else{
            foreach ($data as $k=>$v){
                // 最大可调增成本  = 累计业绩
                // 变更的成本
                $change_crm_oeseng = db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"成本变更","check_status"=>["in",[0,1,2]]])->sum("crm_oeseng");
                // 退回业绩
                $calculate=db("crm_finance")->where(["order_type"=>"退款","receivables_code"=>$v['number'],"check_status"=>["in",[0,1,2]]])->sum("calculate");
                // 回款单业绩
                $refund_calculate = bcsub($v["money"],$v["crm_oeseng"],2);
                // 最大可调增成本 = 业绩金额
                // 业绩=现有金额（回款单核算业绩+成本调整增减业绩）-退回业绩（退款申请）
                $performance = bcsub($refund_calculate,$change_crm_oeseng,2);
                $data[$k]["max_up_oeseng"] = bcadd($performance,$calculate,2);


                // 最大可调减成本  = 核定成本-报销金额
                $expenseMoneySum=db("crm_finance")->where(["receivables_code"=>$v["number"],"order_type"=>"报销","check_status"=>["in",[0,1,2]]])->sum("reimburse_money");//待已报销金额
                // 核定成本 = 现有金额（回款单核定成本-成本调整增减成本）-退回成本（退款金额[仅“金额”，不含追回金额]-退回业绩）
                // 实际退款金额(不含追回金额)
                $should_refund_money=db("crm_finance")->where(["order_type"=>"退款","receivables_code"=>$v['number'],"check_status"=>["in",[0,1,2]]])->sum("should_refund_money");
                // 退回成本 = 退款金额-退回业绩
                $th_crm_oeseng = bcadd($should_refund_money,$calculate,2);
                // 回款单核定成本+成本调整增减成本
                if($change_crm_oeseng > 0) {
                    $crm_oeseng = bcsub($v["crm_oeseng"],$change_crm_oeseng,2);  
                } else {
                    $crm_oeseng = bcadd($v["crm_oeseng"],$change_crm_oeseng,2);
                }
                $max_down_oeseng = bcsub($crm_oeseng,$expenseMoneySum,2);
                $data[$k]['max_down_oeseng'] = bcsub($max_down_oeseng,$th_crm_oeseng,2);
            }
        }
        return resultArray(['data' => $data]);
    }
}
